package com.yonginitagmaker.util;

import java.util.Date;
import java.util.List;

import ra.genius.net.GLog;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

public class CommonUtil
{
	/**
	 * 키패드 숨김
	 * 
	 * @param view
	 *            해당 뷰
	 * @param isHide
	 *            true : 숨김, false : 보임
	 */
	public static void hideKeyPad(View view, boolean isHide)
	{
		InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(view.getContext().INPUT_METHOD_SERVICE);
		if(isHide)
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
		else
			imm.showSoftInput(view, 0);
	}

	/**
	 * 
	 * 문자열의 일부를 하이라이트 처리한다.
	 * 
	 * @param full
	 *            전체 문자열
	 * @param keyword
	 *            하이라이트 문자열
	 * @param originColor
	 *            전체 색깔
	 * @param changeColor
	 *            하이라이트 색깔
	 * @param underLine
	 *            밑줄 유무
	 * @return 바뀐 문자열을 SpannableStringBuilder 형태로 반환
	 */
	public static SpannableStringBuilder highLightStr(String full, String keyword, int originColor, int changeColor, boolean underLine, int size)
	{
		SpannableStringBuilder strBuilder = new SpannableStringBuilder(full);
		if(!FormatUtil.isNullorEmpty(keyword))
		{
			SpannableString spannableStrOrigin = new SpannableString(full);
			spannableStrOrigin.setSpan(new ForegroundColorSpan(originColor), 0, full.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			strBuilder.replace(0, full.length(), spannableStrOrigin);

			SpannableString spannableStr = new SpannableString(keyword);
			if(underLine)
				spannableStr.setSpan(new UnderlineSpan(), 0, keyword.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			spannableStr.setSpan(new ForegroundColorSpan(changeColor), 0, keyword.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			if(size > 0)
				spannableStr.setSpan(new AbsoluteSizeSpan(size), 0, keyword.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

			int keywordStartIndex = full.indexOf(keyword);

			if(keywordStartIndex >= 0)
			{
				strBuilder.replace(keywordStartIndex, keywordStartIndex + keyword.length(), spannableStr);
			}
		}

		return strBuilder;
	}

	/**
	 * 
	 * 문자열의 일부를 하이라이트 처리한다.
	 * 
	 * @param originColor
	 *            전체 색깔
	 * @param changeColor
	 *            하이라이트 색깔
	 * @param underLine
	 *            밑줄 유무
	 * @param full
	 *            전체 문자열
	 * @param keyword
	 *            하이라이트 문자열
	 * @return 바뀐 문자열을 SpannableStringBuilder 형태로 반환
	 */
	public static SpannableStringBuilder highLightStr(int originColor, int changeColor, boolean underLine, int size, String full, String... keyword)
	{
		SpannableStringBuilder strBuilder = new SpannableStringBuilder(full);
		SpannableString spannableStrOrigin = new SpannableString(full);
		spannableStrOrigin.setSpan(new ForegroundColorSpan(originColor), 0, full.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		strBuilder.replace(0, full.length(), spannableStrOrigin);

		if(keyword != null)
		{
			int keywordSize = keyword.length;
			for(int i = 0; i < keywordSize; i ++)
			{
				if(!FormatUtil.isNullorEmpty(keyword[i]))
				{
					SpannableString spannableStr = new SpannableString(keyword[i]);
					if(underLine)
						spannableStr.setSpan(new UnderlineSpan(), 0, keyword[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
					spannableStr.setSpan(new ForegroundColorSpan(changeColor), 0, keyword[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
					if(size > 0)
						spannableStr.setSpan(new AbsoluteSizeSpan(size), 0, keyword[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
	
					int keywordStartIndex = full.indexOf(keyword[i]);
	
					if(keywordStartIndex >= 0)
					{
						strBuilder.replace(keywordStartIndex, keywordStartIndex + keyword[i].length(), spannableStr);
					}
				}
			}
		}

		return strBuilder;
	}

	/**
	 * 디바이스의 가로,세로 화면의 크기를 가져온다.
	 */
	public static int[] getDeviceSize(Context context)
	{
		Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

		int displayWidth = display.getWidth();
		int displayHeight = display.getHeight();

		int[] displaySize = new int[] { displayWidth, displayHeight };

		return displaySize;
	}

	/**
	 * 외장 메모리카드가 장착되어 있는지 파악한다.
	 */
	public static boolean hasSDCard()
	{
		String status = Environment.getExternalStorageState();
		return status.equals(Environment.MEDIA_MOUNTED);
	}

	/**
	 * Flash Player가 설치되어 있는지 파악한다.
	 */
	public static boolean isInstalledFlashPlayer(Context context)
	{
		boolean flashInstalled = false;
		try
		{
			PackageManager pm = context.getPackageManager();
			ApplicationInfo ai = pm.getApplicationInfo("com.adobe.flashplayer", 0);
			if(ai != null)
				flashInstalled = true;
		}
		catch (NameNotFoundException e)
		{
			flashInstalled = false;
		}

		return flashInstalled;
	}

	/**
	 * 특정 어플이 깔려 있는지 확인
	 * 
	 * @param context
	 * @param appName
	 * @return
	 */
	public static boolean isInstallApp(Context context, String appName)
	{
		GLog.i("isInstallApp start!");
		List<PackageInfo> appinfo = context.getPackageManager().getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);

		GLog.i("appinfo.size() : " + appinfo.size());

		for (int i = 0; i < appinfo.size(); i++)
		{
			PackageInfo pi = appinfo.get(i);
			GLog.d("pi.packageName : " + pi.packageName);
			if(pi.packageName.contains(appName))
			{
				GLog.i("is installed!");
				return true;
			}
		}

		GLog.i("is not installed!");
		return false;
	}

	/**
	 * Wifi 가 켜있는지 파악한다.
	 * 
	 * @return
	 */
	public static boolean checkWifi(Context context)
	{
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		return ni.isConnected();
	}

	/**
	 * 현재 버전을 가져온다(versionName)
	 * 
	 * @param context
	 * @return
	 */
	public static String getCurrentVersion(Context context)
	{
		try
		{
			PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionName;
		}
		catch (NameNotFoundException e)
		{
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 현재 디바이스의 전화번호를 가져온다.
	 * 
	 * @param context
	 * @return
	 */
	public static String getTelManager(Context context)
	{
		TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

		String phoneNumber = telManager.getLine1Number();
		if(!FormatUtil.isNullorEmpty(phoneNumber))
			phoneNumber = phoneNumber.replace("+82", "0");
		else
			phoneNumber = "";
		return phoneNumber;
	}

	public static String wrapImgUrl(String imgUrl, int type)
	{
		return imgUrl.replace("/files/", "/" + String.valueOf(type) + "/");

	}

	public static String WrapDateString(String regDt)
	{
		if(FormatUtil.isNullorEmpty(regDt))
		{
			return "";
		}

		Date nowDate = new Date(System.currentTimeMillis());
		Date regDate = FormatUtil.FormatStringGetDate(regDt, "yyyy-MM-dd HH:mm:ss");
		String retDateStr = "";

		long dateGap = getDayTime(nowDate) - getDayTime(regDate);

		if(dateGap < 24 * 60 * 60 * 1000)
		{
			long minute = nowDate.getTime() - regDate.getTime();

			if(minute < 60000)
			{
				retDateStr = "지금";
			}
			else if(minute >= 60000 && minute < 3600000)
			{
				retDateStr = (minute / 60000) + "분전";
			}
			else
			{
				retDateStr = FormatUtil.FormatDateGetString(regDate, "a h:mm");
			}
		}
		else
		{
			long nowDay = nowDate.getDate();
			long regDay = regDate.getDate();

			if(nowDay - regDay == 1)
			{
				retDateStr = FormatUtil.FormatDateGetString(regDate, "어제 a h:mm");
			}
			else
			{
				retDateStr = FormatUtil.FormatDateGetString(regDate, "M.d a h:mm");
			}
		}

		return retDateStr;
	}

	private static long getDayTime(Date date)
	{

		long retVal = date.getTime();

		retVal -= (date.getHours() * 60 * 60 * 1000); // 시간제거
		retVal -= (date.getMinutes() * 60 * 1000); // 분제거
		retVal -= (date.getSeconds() * 1000); // 초제거
		retVal /= 1000; // 밀리초제거
		retVal *= 1000;

		return retVal;

	}

	public static float dipToPixel(Context context, int dip)
	{
		return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, context.getResources().getDisplayMetrics());
	}

	public static boolean isActivityOn(Context context, String className)
	{
		boolean isActivityOn = true;
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> info = activityManager.getRunningTasks(100);
		GLog.e("className----->" + className);
		for (RunningTaskInfo runningTaskInfo : info)
		{
			String baseAct = runningTaskInfo.baseActivity.getClassName().toString();
			String topAct = runningTaskInfo.topActivity.getClassName().toString();

			GLog.e("topActivity----->" + baseAct);
			GLog.e("baseActivity----->" + topAct);

			if(baseAct.contains(className))
			{
				isActivityOn = false;
				break;
			}
		}
		if(info != null)
		{
			info.clear();
		}
		if(activityManager != null)
		{
			activityManager = null;
		}

		return isActivityOn;
	}

	public static boolean isProviderOn(Context context)
	{
		boolean result = false;
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		boolean networkOn = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		boolean gpsOn = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

		locationManager = null;
		result = networkOn || networkOn;

		return result;
	}
}